﻿using System;
using System.Linq;
using Shell.PocoDot.Configurations;

namespace Shell.PocoDot
{
    public class EfRepositoryFactory : IRepositoryFactory
    {
        public IRepository Create(Type mainPocoDot, Type relatedPocoDot)
        {
            return this.CreateRepository(mainPocoDot, relatedPocoDot);
        }

        protected virtual IRepository CreateRepository(Type mainPocoDot, Type relatedPocoDot)
        {
            var configs = RelationRegistrar.Registrar.Configurations;
            var config = configs.SingleOrDefault(c => c.MainPocoDot == mainPocoDot && c.RelatedPocoDot == relatedPocoDot);
            if (config == null)
            {
                config = configs.SingleOrDefault(c => c.RelatedPocoDot == mainPocoDot && c.MainPocoDot == relatedPocoDot);
                if (config == null)
                {
                    var errormsg = SR.Get("Error.RelationNotFound", mainPocoDot.Name, relatedPocoDot.Name);
                    throw new InvalidOperationException(errormsg);
                }
                return new EfReversedRepository(config);
            }
            return new EfRepository(config);
        }
    }
}
